<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">


      <el-row :gutter="20">
        <el-col :span="7">
          <div class="mt-4">
            <el-input
                clearable
                placeholder="请输入搜索内容"
                class="input-with-select"
                v-model="queryInfo.query"
                @clear="getUserList"
            >
              <template #append>
                <el-button :icon="Search()" @click="getUserList"/>
              </template>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserVi">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="usersList" stripe style="width: 100%" border>
        <el-table-column type="index" width="50" label="@"/>
        <el-table-column prop="username" label="姓名"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="mobile" label="电话"/>
        <el-table-column prop="role_name" label="角色"/>
        <el-table-column label="状态">
          <template v-slot:default="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"/>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="160x">
          <template v-slot:default="scope">
            <el-button type="primary" :icon="Edit()" size="small" @click="showEditDialog(scope.row.id)"/>
            <el-button type="danger" :icon="Delete()" size="small" @click="removeUserById(scope.row.id)"/>
            <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
            >
              <el-button type="warning" :icon="Setting()" size="small" @click="setRole(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
          v-model:current-page="queryInfo.pagenum"
          v-model:page-size="queryInfo.pagesize"
          :page-sizes="[1, 2, 5, 10]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="usersTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
      />
    </el-card>

    <el-dialog v-model="dialogTableVisible" title="添加用户" @close="addDialogClosed">
      <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"/>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"/>
        </el-form-item>
      </el-form>


      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialogTableVisible" title="修改用户信息" @close="editFormClose">
      <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="120px"
      >
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="editForm.username" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" >
          <el-input v-model="editForm.email"/>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" >
          <el-input v-model="editForm.mobile"/>
        </el-form-item>
      </el-form>


      <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo">确定</el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="setRoleDialogVisible"
        title="分配角色"
        width="50%"
        @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" class="m-2" placeholder="请选择" size="large">
            <el-option
                v-for="role in rolesList"
                :key="role.id"
                :label="role.roleName"
                :value="role.id"
            />
          </el-select>
        </p>

      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateRoleInfo">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import {Delete, Edit, Search, Setting} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";

export default {
  name: "Users",
  data() {

    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        return cb();
      } else {
        return cb(new Error('请输入合法邮箱'));
      }

    };

    var checkMobile = (rule, value, cb) => {
      const regEmail = /^1[3456789]\d{9}$/;
      if (regEmail.test(value)) {
        return cb();
      } else {
        return cb(new Error('请输入合法手机号'));
      }
    };
    return {
      setRoleDialogVisible : false,
      rolesList:[],
      userInfo: null,
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      usersList: [],
      usersTotal: 0,
      dialogTableVisible: false,
      editDialogTableVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '用户名的长度在 3 到 10 之间', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '密码的长度在 6 到 15 之间', trigger: 'blur'},
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      editForm: {
        id :'',
        username: '',
        email: '',
        mobile: '',
      },
      editFormRules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      selectedRoleId: '',

    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    setRoleDialogClosed(){
      this.selectedRoleId = ''
      this.userInfo = null
    },
    async updateRoleInfo() {
      if (this.selectedRoleId !== '') {
        const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, {rid: this.selectedRoleId})
        await this.getUserList()
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }else{
          this.$message.success(res.meta.msg)
        }
      }else{
        return this.$message.error("未知错误");
      }
      return this.setRoleDialogVisible = false
    },
    async setRole(userInfo) {
      this.userInfo = userInfo

      const {data: res} = await this.$http.get('roles');
      this.rolesList = res.data
      this.setRoleDialogVisible = true

      return (res.meta.status === 200) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);
    },
    Setting() {
      return Setting
    },
    Delete() {
      return Delete
    },
    Edit() {
      return Edit
    },
    Search() {
      return Search
    },
    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo})
      if (res.meta.status !== 200) {
        return ElMessage.error('"获取用户列表失败');
      }
      this.usersList = res.data.users;
      this.usersTotal = res.data.total;
      // console.log(res)
    },
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async userStateChanged(userInfo) {
      // console.log(userInfo)
      const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return ElMessage.error('更新用户状态失败');
      }
      ElMessage.success('更新用户状态成功');
    },
    addUserVi() {
      this.dialogTableVisible = true
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    async addUser() {

      await this.$refs.addFormRef.validate(async v => {
        if (!v) {
          this.$message.error("信息格式错误")
          return
        } else {
          const {data: res} = await this.$http.post(`users`, this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg)
            await this.getUserList()
            this.dialogTableVisible = false
          }
        }

      })

    },
    async showEditDialog(id) {
      this.editDialogTableVisible = true;
      const {data: res} = await this.$http.get('users/' + id.toString())
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }else{
        this.editForm = res.data
      }
    },
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async v => {
        if (!v) return
        else {
          // alert(this.editForm.id)
          const {data: res} = await this.$http.put(`users/${this.editForm.id}`,{
            email: this.editForm.email,
            mobile: this.editForm.mobile
          } );

          if(res.meta.status !== 200){
            this.$message.error(res.meta.msg)
          }else{
            await this.getUserList()

            this.editDialogTableVisible = false

            this.$message.success(res.meta.msg)
          }
        }
      })
    },
    removeUserById(id){
      //

      this.$confirm(
            '此操作将永久删除用户，请确认！',
            '警告',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
        ).then(async () => {
        const {data: res} = await this.$http.delete(`users/${id}`);
        if(res.meta.status !== 200){
          this.$message.warning(res.meta.msg)
        }else{
          await this.getUserList()
          this.$message.success(res.meta.msg)
        }

      }).catch(() => {
        this.$message.info('已取消删除操作');
      })


    }


  }
}
</script>

<style scoped>

</style>